package org.visionlibrary.image.filters.rescaling;

import javax.media.jai.TiledImage;

import org.visionlibrary.image.acquisition.ImageFactory;
import org.visionlibrary.image.model.AbstractFilter;


public class Monochromatic extends AbstractFilter {
	private int[] color;

	public Monochromatic(int[] color) {
		this.color = color;
	}

	public Monochromatic() {
		color = new int[] { 182, 140, 90 };
	}

	public TiledImage applyFilter(TiledImage src, TiledImage dest) {
		if (null == src)
			throw new NullPointerException("Source image is null.");

		if (null == dest)
			dest = (new ImageFactory()).createCompatibleImage(src);

		if (color.length != src.getNumBands())
			throw new IllegalArgumentException(
					"Given color and source image have different number of channels");

		int maxX = src.getWidth();
		int maxY = src.getHeight();

		int[][] lut = new int[256][src.getNumBands()];

		for (int ch = 0; ch < src.getNumBands(); ch++)
			for (int i = 0; i < 256; i++)
				lut[i][ch] = (int) ((float) i * (float) color[ch] / 255.0f);

		for (int x = 0; x < maxX; x++)
			for (int y = 0; y < maxY; y++) {
				int sum = 0;
				for (int ch = 0; ch < src.getNumBands(); ch++)
					sum += src.getSample(x, y, ch);
				sum /= 3;

				for (int ch = 0; ch < src.getNumBands(); ch++)
					dest.setSample(x, y, ch, normalization
							.normalize(lut[sum][ch]));
			}

		return dest;
	}
}
